package server

import (
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

func checkError(err error) {
	if err != nil {
		panic(err)
	}
}
func userLogin(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		fmt.Fprintf(w, "Only POST Method")
		return
	}
	r.ParseForm()
	fmt.Println(r.Form)
	id, err := strconv.Atoi(r.Form["id"][0])
	println(id)
	checkError(err)

}

func test(c *gin.Context) {
	//fmt.Println("test")
	c.JSON(http.StatusOK, gin.H{
		"msg": "Hello",
	})
}
func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("test")
}
func register(w http.ResponseWriter, r *http.Request) {
	fmt.Println("test")
}

func CorsHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "true")
		c.Header("Access-Control-Allow-Headers", "*")
		c.Header("Access-Control-Allow-Methods", "POST, GET, PUT, PATCH, OPTIONS")
		c.Header("Access-Control-Allow-Credentials", "true")
		c.Header("Access-Control-Expose-Headers", "*")
		if c.Request.Method == "OPTIONS" {
			c.JSON(http.StatusOK, "")
			c.Abort()
			return
		}
		c.Next()
	}

}

// 解决跨域问题
func Core() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "*")
		c.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT")
		c.Header("Access-Control-Expose-Headers", "Content-Length,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Type")
		c.Header("Access-Control-Allow-Credentials", "True")
		//放行索引options
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		//处理请求
		c.Next()
	}
}
func StartServer() *gin.Engine {
	r := gin.Default()
	config := cors.DefaultConfig()
	config.AllowAllOrigins = true
	r.Use(cors.New(config))
	fmt.Println(r.BasePath())
	r.POST("/data", test)
	//r.POST("/api/login", login)
	//r.POST("/api/register", register)
	err := http.ListenAndServe(":5200", nil)
	if err != nil {
		log.Fatal("ListenAndServer: ", err)
	}
	return r
}
